const app = getApp()
const api = require('../../utils/api.js')
// let QRcode = ''

// function getQRcode() {
//   var that = this
//   api.post('user/getUnlimited', {
//     shopId: app.globalData.shopId,
//     userId: wx.getStorageSync('user').userId + ''
//   }).then(res => {
//     QRcode = res.data.data

//   })
// }
// getQRcode()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: '',
    windowWidth: '',
    posterHeight: '',
    hidden: true,
    earningsAmount: 0, //累计金额
    inviterNum: 0, //累计推广
    orders: 0, // 推广订单
    userName: '', // 推荐人
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    const poster = {
      "with": 638,
      "height": 1168
    }
    const systemInfo = wx.getSystemInfoSync()
    let windowWidth = systemInfo.windowWidth
    let windowHeight = systemInfo.windowHeight
    let posterHeight = parseInt((windowWidth / poster.with) * poster.height)
    this.setData({
      windowWidth: windowWidth,
      posterHeight: posterHeight,

    })



  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    let QRcode
    this.getInfo();
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              that.setData({
                userInfo: res.userInfo
              })
              that.drawImg(res.userInfo)
            }
          })
        }
      }
    })


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (ops) {
    this.setData({
      hidden: true
    })
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    console.log('pages/getCoupon/index?parentId='+ wx.getStorageSync('user').userId )
    return {
      title: app.globalData.appName,
      path: 'pages/getCoupon/index?parentId='+ wx.getStorageSync('user').userId ,
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
   
  },
  /* 绘制图片 */
  drawImg: function (userInfo) {
    let canvasW = this.data.windowWidth // 画布的真实宽度
    let bgHeight = this.data.windowWidth * (1168 / 638)
    let bg = new Promise(function (resolve, reject) {
      /* 获得要在画布上绘制的图片 */
      wx.getImageInfo({
        src: '../../images/invitebg.png',
        success: function (res) {

          resolve(res);
        }
      })
    });
    let avator = new Promise(function (resolve, reject) {
      /* 获得要在画布上绘制的图片 */
      wx.getImageInfo({
        src: userInfo.avatarUrl,
        success: function (res) {
          console.log(res, 'getImageInfo', userInfo.avatarUrl)
          resolve(res);
        }
      })
    });
    let QRimg = new Promise(function (resolve, reject) {
      let QRcode;
      api.post('user/getUnlimited', {
        shopId: app.globalData.shopId,
        userId: wx.getStorageSync('user').userId + ''
      }).then(response => {
        /* 获得要在画布上绘制的图片 */
        wx.getImageInfo({
          src: response.data.data,
          success: function (res) {
            console.log(res, 'QRcode', QRcode)
            resolve(res);
          }
        })

      })

    });
    Promise.all(
      [bg, avator, QRimg]
    ).then(res => {
      /* 创建 canvas 画布 */
      const ctx = wx.createCanvasContext('shareImg')
      /* 绘制图像到画布  图片的位置你自己计算好就行 参数的含义看文档 */
      /* ps: 网络图片的话 就不用加../../路径了 反正我这里路径得加 */
      ctx.drawImage('../../' + res[0].path, 0, 0, canvasW, bgHeight);
      ctx.drawImage(res[2].path, canvasW/3, 450, 120, 120);
      ctx.stroke();
      ctx.setFontSize(18);
      ctx.setFillStyle('#6C53F2');
      ctx.setTextAlign('center');
      ctx.fillText(userInfo.nickName, canvasW / 2, 385);
      ctx.stroke();
      ctx.setFontSize(18);
      ctx.setFillStyle('#6C53F2');
      ctx.setTextAlign('center');
      ctx.fillText("发现一堆优惠券，快来领取！", canvasW / 2, 425);
      ctx.stroke();
      ctx.setFontSize(18);
      ctx.setFillStyle('#6C53F2');
      ctx.setTextAlign('center');
      ctx.fillText("长按识别小程序", canvasW / 2, 605);
      ctx.stroke();
      ctx.arc(canvasW / 2, 300, 50, 0, 2 * Math.PI) //画出圆
      ctx.strokeStyle = "#fff";
      ctx.clip(); //裁剪上面的圆形
      ctx.drawImage(res[1].path, canvasW/2-50, 250, 100, 100); // 在刚刚裁剪的园上画图
      /* 绘制 */
      ctx.stroke();

      ctx.draw();

      // setTimeout(function () {
      //   wx.canvasToTempFilePath({
      //     canvasId: 'shareImg',
      //     success: function (res) {
      //       var tempFilePath = res.tempFilePath;
      //       that.setData({

      //       });
      //     }
      //   })
      // })

    })
  },

  /*生成预览图片  */
  showPreview: function () {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      destWidth: 638,
      destHeight: 1168,
      canvasId: 'shareImg',
      success: function (res) {
        console.log(res.tempFilePath);
        that.setData({
          prurl: res.tempFilePath,
          hidden: false
        })
        wx.hideLoading()
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  /* 保存 */
  save: function () {
    var that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 没有相册授权
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.saveImg();
            },
            fail() {
              wx.openSetting({
                success: res => {

                }
              })
            }
          });
        } else {
          // 有相册授权
          that.saveImg();
        }
      }
    })
  },
  close: function () {
    this.setData({
      hidden: true
    })
  },

  /* 保存图片到相册 */
  saveImg: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.prurl,
      success: function (res) {
        wx.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 1500
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '保存失败，请重试',
          icon: 'none',
          duration: 1500
        })
      }
    })
    this.setData({
      hidden: true
    })
  },
  /* 跳转收益明细 */
  goIncome: function () {
    wx.navigateTo({
      url: '/pages/income/index'
    })
  },
  /* 获取分销详情 */
  getInfo: function () {
    var that = this;
    api.post('distribution/front/user/account/info', {
      bid: app.globalData.shopId,
      shopId: app.globalData.shopId,
      userId: wx.getStorageSync('user').userId + ''
    }).then(res => {
      that.setData({
        earningsAmount: res.data.data.earningsAmount / 100,
        inviterNum: res.data.data.inviterNum,
        orders: res.data.data.orders,
        userName: res.data.data.userName
      })
    })
  },
  /* 跳转订单明细 */
  goOrdersInvite: function () {
    wx.navigateTo({
      url: '/pages/order/index?actId='+0
    })
  },
  goOrdersOrders:function() {
    wx.navigateTo({
      url: '/pages/order/index?actId='+1
    })
  }
})